const BASE_URL = import.meta.env.VITE_API_BASE_URL;

import type { ApiResponse } from '../../../server/shared/types.ts';

async function handleResponse<T>(response: Response): Promise<T> {
  const result = await response.json() as ApiResponse<T>;
  
  if (!response.ok || !result.success) {
    throw new Error(result.message || '请求失败');
  }
  
  return result.data as T;
}

export async function fetchApi<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = endpoint.startsWith('http') 
    ? endpoint 
    : `${BASE_URL}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`;

  const response = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  return handleResponse<T>(response);
}

// 用于调试
if (import.meta.env.DEV) {
  console.log('API Base URL:', BASE_URL);
} 